import { cloneDeep } from 'lodash'
const LS = window.localStorage
const storageName = 'db_ecoupons'
const commonStorage = 'db_common'
let dbObj: any = {}
let commonObj: any = {}

interface Db {
  readonly initCommon: () => void
  readonly init: () => void
  readonly set: (key: string, value: any) => void
  readonly get: (key: string) => any
  readonly remove: (key: string) => void
  readonly clear: () => void
  readonly setCommon: (key: string, value: any) => void
  readonly getCommon: (key: string) => any
  readonly removeCommon: (key: string) => void
  readonly clearCommon: () => void
}

const db: Db = {
  init() {
    const dbString: string | null = LS.getItem(storageName)
    this.initCommon()
    if (dbString) {
      try {
        dbObj = JSON.parse(dbString)
      } catch (error) {
        LS.setItem(storageName, JSON.stringify({}))
        console.log('db error')
      }
    }
  },
  initCommon() {
    const dbString: string | null = LS.getItem(commonStorage)
    if (dbString) {
      try {
        commonObj = JSON.parse(dbString)
      } catch (error) {
        LS.setItem(commonStorage, JSON.stringify({}))
        console.log('db error')
      }
    }
  },
  setCommon(key: string, value: any) {
    commonObj[key] = value
    LS.setItem(commonStorage, JSON.stringify(commonObj))
  },
  getCommon(key: string) {
    return cloneDeep(commonObj[key])
  },
  removeCommon(key: string) {
    delete commonObj[key]
    LS.setItem(commonStorage, JSON.stringify(commonObj))
  },
  clearCommon() {
    commonObj = {}
    LS.setItem(commonStorage, JSON.stringify(commonObj))
  },
  set(key: string, value: any) {
    dbObj[key] = value
    LS.setItem(storageName, JSON.stringify(dbObj))
  },
  get(key: string) {
    return cloneDeep(dbObj[key])
  },
  remove(key: string) {
    delete dbObj[key]
    LS.setItem(storageName, JSON.stringify(dbObj))
  },
  clear() {
    dbObj = {}
    LS.setItem(storageName, JSON.stringify(dbObj))
  }
}
export default db
